import sched

import threading
import os
import random
import time
from multiprocessing import Queue

"""
多线程的设计: 
    import threading
    多线程相比多进程的区别:
        多线程更加轻量化,使得io处理更加迅速
        
    # 面向对象的设计模式
        继承Thread类,重写run()方法
        设置守护进程,thread.setDaemon(True)
    
    # lock模块存在的问题
    上了几次锁就要解锁几次,就很不方便
    于是出现了rLock --- 一次解除所有锁
            
# 调度sched
    安排,指定程序在什么时候去执行,
    这里的调度只能实现时间间隔调度,
    如果是指定时间调度就要配合其他模块


# 生产者消费者
    生产一个消费一个
    没有产品就阻塞  
           
"""


# 模型:生产炸鸡,厨房生产出来炸鸡,通知顾客消费

class Chicken:
    def __init__(self):
        self.__id = None # 每个鸡有一个id号

    def set_id(self,id):
        self.__id =id

    def get_id(self):
        return self.__id

    def __str__(self):
        return self.__id


class Cooking(threading.Thread):
    def __init__(self,name,id,queue):
        super().__init__(name=name)
        self.__id = id
        self.__queue = queue

    def cook(self):
        time.sleep(random.randint(1, 4))
        chicken = Chicken()
        chicken.set_id(self.__id)
        self.__queue.put(chicken)
        print('{} 把{}号鸡做好了 {}'.format(threading.current_thread().name,self.__id,time.time()))


    def run(self) -> None:
        self.cook()


class Customer(threading.Thread):
    def __init__(self,name,queue):
        super().__init__(name=name)
        self.__queue = queue

    def eat(self):
        try:
            chicken = self.__queue.get(block=True,timeout=5)
            print('{}顾客吃了{}  {}'.format(threading.current_thread().name,chicken.get_id(),time.time()))
        except:
            print('没有鸡了')

    def run(self) -> None:
        self.eat()


def main():
    queue = Queue()
    cookers = [Cooking(name='厨师{}'.format(item),id=item,queue=queue) for item in range(10)]
    customers = [Customer(name='顾客{}'.format(item),queue=queue) for item in range(10)]
    for cooker in cookers:
        cooker.start()
    for customer in customers:
        customer.start()
    for cooker in cookers:
        cooker.join()
    for customer in customers:
        customer.join()


if __name__ == '__main__':
    main()